<?php
namespace command\factory\api;

use base\tools\HttpHelper;

/**
 * yapi接口对接服务
 */
class YapiService
{

    /**
     * 接口数据文件路径
     *
     * @var string
     */
    private $dataFile = '';

    /**
     * 接口数据
     *
     * @var array
     */
    private $data=[];

    /**
     * yapi项目配置
     *
     * @var array
     */
    private $config = [
        'index'=>['token'=>'','project_id'=>''],
        'admin'=>['token'=>'','project_id'=>''],
    ];

    /**当前有效配置 */
    private $curConfig = [];

    /**yapi地址 */
    private $url = 'http://api.yokesoft.cn/';

    /**
     * 构造函数 初始化数据和配置
     *
     * @param [type] $module
     */
    public function __construct($module)
    {
        $dataPath = __DIR__ .  DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR;

        if(!is_dir($dataPath)){
            mkdir($dataPath,0777,true);
        }

        $this->dataFile = $dataPath . $module . 'api.json';

        if(!empty(config('ykcommand')['yapi'])){
            $this->config = config('ykcommand')['yapi'];
        }

        $this->curConfig = $this->config[$module]??NULL;

        if(!$this->curConfig)return_error(['info'=>'获取接口项目失败']);

        if(!is_file($this->dataFile)){
            file_put_contents($this->dataFile,json_encode($this->data));
        }else{
            $info = file_get_contents($this->dataFile);
            $this->data = json_decode($info,true);
        }
    }

    /**
     * 同步API信息
     *
     * @param array $apiInfo API信息
     * @return void
     */
    public function syncApi($apiInfo)
    {
        $catid = $this->getApiCate($apiInfo['cate_name']);

        $apiInfo['catid']=$catid;

        $apiid = $this->saveInterface($apiInfo);

        if($apiid) $this->data['api'][$apiInfo['path']]=$apiid;
        
    }

    /**
     * 根据分类名称获取分类ID
     *
     * @param string $name
     * @return void
     */
    private function getApiCate($name)
    {
        $catInfo = $this->data['cat'][$name]??null;

        if($catInfo){
            return $catInfo['catid'];
        }else{
            $catid = $this->addApiCate($name);
            if($catid){
                $this->data['cat'][$name]=['catid'=>$catid,'name'=>$name,'desc'=>$name];
                return $catid;
            }

            return_error(['info'=>'获取接口分类错误']);
        }
    }

    /**
     * 新增分类
     *
     * @param string $name
     * @return void
     */
    private function addApiCate($name)
    {
        $url = $this->url.'api/interface/add_cat';

        $data = ['name'=>$name,'desc'=>$name,'token'=>$this->curConfig['token'],'project_id'=>$this->curConfig['project_id']];

        $res = HttpHelper::curl($url,"POST",$data);

        $res = json_decode($res,true);

        if($res['errcode']==0){
            return $res['data']['_id'];
        }
        return_error(['info'=>$res['errmsg']]);
    }

    /**
     * 更新或新增接口
     *
     * @param array $apiInfo
     * @return void
     */
    private function saveInterface($apiInfo)
    {
        $apiData = [
            'token'=>$this->curConfig['token'],
            'req_query'=>[],
            'req_headers'=>[],
            'req_body_form'=>[],
            'title'=>$apiInfo['title'],
            'catid'=>$apiInfo['catid'],
            'path'=>$apiInfo['path'],
            'status'=>'undone',
            'res_body_type'=>'json',
            'res_body'=>'',
            'switch_notice'=>false,
            'desc'=>'',
            'method'=>$apiInfo['http_method'],
            'req_params'=>[],
            "req_body_is_json_schema"=>true,
            "res_body_is_json_schema"=>true
        ];

        $req_headers=[];
        if(empty($apiInfo['except_token'])){
            $req_headers[] = [
                    "required"=>"1",
                    "name"=>"token",
                    "value"=>""
            ];
        }

        if($apiInfo['http_method']=='post'){
            $req_headers[] = [
                "required"=>"1",
                "name"=>"Content-Type",
                "value"=>"application/x-www-form-urlencoded"
            ];
            $apiData['req_body_form']=$apiInfo['req'];
            $apiData['req_body_type']='form';
        }else{
            $apiData['req_query']=$apiInfo['req'];
        }

        $apiData['req_headers']=$req_headers;

        $id = $this->getApi($apiData['path']);

        if($id){
            $apiData['id']=$id;
        }

        $url = $this->url.'api/interface/save';

        $res = HttpHelper::curl($url,"POST",json_encode($apiData),['Content-Type'=>'application/json']);

        $res = json_decode($res,true);

        if($res['errcode']==0){
            return $res['data'][0]['_id']??0;
        }
        return_error(['info'=>$res['errmsg']]);
        
    }
    
    /**
     * 获取api对应ID
     *
     * @param string $path
     * @return void
     */
    private function getApi($path)
    {
        return $this->data['api'][$path]??0;
    }

    /**
     * 析构函数，将数据保存到文件
     */
    public function __destruct()
    {
        file_put_contents($this->dataFile,json_encode($this->data,JSON_UNESCAPED_UNICODE));
    }
}